<template>
	<div class="app-container" v-loading="loading">
		
		<div class="search-container  app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="4">
						<el-tree-select  v-model="queryParams.cid"
							:data="baseConfigStore.newExCompanyList" check-strictly :render-after-expand="false"
							placeholder="请选择所属公司">
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-col>
				
					<el-col :span="6" >
						<el-button  :loading="loading"  type="primary" @click="handleQuery"><template
							#icon><i-ep-search /></template>查询</el-button>
					</el-col>
				</el-row>
				<FilterColumn
				 class="filtBox"
				 @handleRefresh="resetQuery()"
				:strtype="strtype"></FilterColumn>
			</div>	
		</div>
		

		<el-card shadow="never">
			
			<div class="action-row">
				<el-button v-hasPerm="['ApproveTemplateSave']" type="primary" @click="handleDo('','act_add')" plain><template #icon><i-ep-plus /></template>新增</el-button>
				<el-button v-hasPerm="['ApproveTemplateUpdate']" @click="handleDo('', 'act_edit')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-edit/></template>修改</el-button>
				<el-button v-hasPerm="['ApproveTemplateDel']" @click="handleDo('', 'act_del')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-delete/></template>删除</el-button>
			</div>
			
			
			<el-table ref="dataTableRef" 
				v-loading="loading" 
				:data="dataList" 
				align="left" 
				tooltip-effect="dark"
				:show-overflow-tooltip="true" 
				:scrollbar-always-on="true" border
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" fixed="left" align="center" width="55" />
				<el-table-column type="index" label="序号" align="center" width="80" />
				<el-table-column label="所属公司" align="center" prop="company.name" min-width="150"></el-table-column>
				<el-table-column label="审批流类型" align="center" prop="type" min-width="150">
					<template #default="scope">
						{{retrunType(scope.row.type)}}
					</template>
				</el-table-column>
			</el-table>
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card> 
		
		<!--表单-->
		<el-dialog 
			:title="formText" 
			v-model="dialogFormVisible" lock-scroll 
			width="1000px"
			:close-on-click-modal="false" 
			:close-on-press-escape="false" class="list-info">
			<div v-if="['act_add','act_edit'].includes(dialogStatus)">
				<el-form ref="dataFormRef" :model="formTemp" :rules="formRules" label-position="right"
					label-width="150px">
					<el-form-item label="所属公司：" prop="cid">
						<el-tree-select class="defalut-width2" v-model="formTemp.cid"
							:data="baseConfigStore.newExCompanyList" check-strictly :render-after-expand="false"
							placeholder="请选择所属公司">
							<template v-slot:default="{node, data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-form-item>
					<el-form-item label="审批流类型：" prop="type">
						<el-select
						     v-model="formTemp.type"
						     placeholder="请选择审批流类型"
						     class="defalut-width" >
						     <el-option v-for="item in approveType"  :label="item.title" :value="item.value"/>
						   </el-select>
					</el-form-item>
					<el-form-item label="流程设置：" prop="rule">
						
						<el-table 
							:data="fromTempTable" 
							align="left" 
							tooltip-effect="dark"
							:show-overflow-tooltip="true" 
							:scrollbar-always-on="true" border>
							
							<el-table-column label="顺序" type="index" align="center" width="80">
								<template #default="scope">
									<div class="el-step is-vertical" style="flex-basis: 50%; padding: inherit;">
									  <div class="el-step__head is-finish">
									    <div class="el-step__line" style="margin-right: 0;">
									      <i class="el-step__line-inner" style="transition-delay: 0ms; border-width: 0; height: 0;" />
									    </div>
									    <div class="el-step__icon is-text">
									      <div class="el-step__icon-inner">{{ scope.$index+1 }}</div>
									    </div>
									  </div>
									</div>
								</template>
							</el-table-column>
							<el-table-column label="部门名称" align="center" prop="name" min-width="150">
								<template #default="scope">
									<el-input v-model="scope.row.name" placeholder="请输入部门名称" clearable/>
								</template>
							</el-table-column>
							<el-table-column label="审批方式" align="center" prop="type" min-width="150">
								<template #default="scope">
									<el-select
									     v-model="scope.row.type"
									     placeholder="请选择审审批方式"
									     style="width: 100%;" >
									     <el-option v-for="item in approveStatus"  :label="item.title" :value="item.value"/>
									   </el-select>
								</template>
							</el-table-column>
							<el-table-column label="审批人" align="center"  min-width="150">
								<template #default="scope">
									<span v-if="scope.row.type == 1" class="perfect_rule" 
										 @click="perfectCon(scope.$index,scope.row)">
										 <span v-if="scope.row.userInfo.length>0">编辑({{scope.row.userInfo.length}})</span>
										 <span v-else>完善规则</span>	
									</span>
									<el-select v-else-if="scope.row.type == 2"
									     v-model="scope.row.level"
									     placeholder="请选择层级"
									     style="width: 100%;">
									     <el-option v-for="item in approveLevel"  :label="item.title" :value="item.value"/>
									</el-select>
								</template>
							</el-table-column>
							<el-table-column label="操作" align="center" prop="type" min-width="150">
								<template #default="scope">
									<div>
										<!-- -->
										<el-icon class="el-icon-circle-plus-outline w20'" style="padding-left: 5px;" />
										<el-button type="text"  @click="addRow(scope.$index+1)">添加</el-button>
										<el-icon v-if="scope.$index>0" class="el-icon-delete w20'" style="padding-left: 20px; color: #F56C6C;" />
										<el-button v-if="scope.$index>0" type="text" style="color: #F56C6C;" @click="deleteRow(scope.$index)">删除</el-button>
									</div>
								</template>
							</el-table-column>
						</el-table>
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button v-if="['act_add','act_edit'].includes(dialogStatus)" v-no-more-click type="primary"
						@click="doData(dialogStatus)">提 交</el-button>
					<el-button @click="dialogFormVisible = false">关闭</el-button>
				</div>
			</template>
		</el-dialog>
		
		
		<!--表单-->
		<el-dialog 
			title="完善人员" 
			v-model="dialogApproveVisible" 
			lock-scroll 
			width="1000px"
			:close-on-click-modal="false" 
			:close-on-press-escape="false">
			<div class="appCont">
				<!-- {{departmentAndUserList}} -->
				<div class="appContLeft">
					<el-tree ref="treeRef" 
						node-key="id" 
						:data="departmentAndUserList" 
						:default-expanded-keys="[1]"
						:check-on-click-node="true" 
						:show-checkbox="true"
						@check="nodeClickDown"
						:props="{'children': 'children','label':'name','value':'id','disabled':'disable'}">
						<template #default="{ node, data }">
							
							<div class="lineDiv">
								<div  v-if="data.type  !=1 && data.type  !=2" class="lineimgs">
									<img class="lineimg" style="width: 20px;height: 20px;" :src="data.avatar" alt="">
								</div>
								<div class="lineTx">
									{{ node.label }} <span v-if="data.type  !=1 && data.type  !=2">- {{data.position}}</span>
								</div>
							</div>
						</template>
					</el-tree>
				</div>
				<div class="appContRight">
					<div class="apli" v-for="item in downPeoples">
						 <el-avatar :size="40" :src="item.avatar" />
						 <span style="margin-right: 10px;margin-left: 10px;">{{item.name}}</span>
						 <span style="margin-right: 10px;">{{item.position}}</span>
					</div>
				</div>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="getAllkeys">确定</el-button>
					<el-button @click="dialogApproveVisible = false">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts">

	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	//接口地址
	import {
		getDepartmentAndUser
	} from "@/api/doc";
	//接口地址
	import {
		approveTemplateAdd,
		approveTemplateEdit,
		approveTemplateList,
		approveTemplateInfo,
		approveTemplateDel,
	} from "@/api/approve";
	
	const baseConfigStore = useBaseConfigStore();
	const strtype = ref('systemApprove'); //数据
	
	// 表单模型
	const cForm = {
		id:undefined,//模板id
		cid:"",//公司id
		type:"",//审批流类型 
		rule:[] //审批规则
	}
	// 验证规则
	const cRules = {
		cid: [{required: true,message: '请选择所属公司',trigger: 'change'}],
		type: [{required: true,message: '请选择审批流类型',trigger: 'change'}],
	}
	// 表单节点模型
	const cRow = {
		 name:"",//所属公司
		 type:"",//审批流类型
		 user:[], //用户
		 level:[],//等级
		 userInfo:[], //人员配置
	}
	

	/*** 搜索窗-字段表 */
	const queryParams = reactive({
		page: 1,
		limit: 20,
		cid:""
	});
	const loading = ref(false);//页面加载load
	const ids = ref<number[]>([]);
	const total = ref(0);
	const dataList = ref<any>();
	const formTemp = ref<any>(JSON.parse(JSON.stringify(cForm)));
	const formRules = ref<any>(JSON.parse(JSON.stringify(cRules)));//验证规则
	const departmentAndUserList =ref([]);//审批人
	
	const multipleSelection =ref<any>([]);
	// const menuLineVisible =ref(true);
	// const rowR = ref<any>({});
	const dataFormRef = ref(ElForm);
	const dialogFormVisible = ref<boolean>(false);//表单
	const dialogApproveVisible =ref<boolean>(false);//审批人
	const dialogStatus = ref<string>(""); // 操作行为 formText
	const formText =ref<string>(""); // 操作窗口标题
	
	const fromTempTable =ref([JSON.parse(JSON.stringify(cRow))]);
	
	const approveType=ref([
		{title:'公文',value:1},
		{title:'合同会签',value:2},
		{title:'合同审批',value:3},
		{title:'法务审计',value:4},
		{title:'工程合同支付申请',value:5},
		{title:'资金申请',value:6},
		{title:'发票入账单',value:7},
	])
	
	const approveStatus=ref([
		{title:'指定成员',value:1},
		{title:'指定上级',value:2},
	])
	
	const approveLevel=ref([
		{title:'直属上级',value:1},
		{title:'第二级上级',value:2},
		{title:'第三级上级',value:3},
		{title:'第四级上级',value:4},
		{title:'第五级上级',value:5},
		{title:'第六级上级',value:6},
		{title:'第七级上级',value:7},
		{title:'第八级上级',value:8},
		{title:'第九级上级',value:9},
		{title:'第十级上级',value:10},
	])
	
	// 返回审批流类型
	function retrunType(type:any){
		let result:any =approveType.value.filter(item => item.value == type);
		return result[0].title;
	}
	
	
	function handleQuery(){
		loading.value = true;
		console.log('加载数据')
		approveTemplateList(queryParams).then((res) => {
			dataList.value = res.data.list
			total.value = res.data.count
		}).finally(() => {
			loading.value = false;
		})
	}
	
	// 添加一行
	function addRow(index:number) {
	  const tempData = JSON.parse(JSON.stringify(cRow))
	  fromTempTable.value= fromTempTable.value.slice(0, index).concat(tempData, fromTempTable.value.slice(index))
	}
	
	// 删除一行
	function deleteRow(index:number) {
	    fromTempTable.value.splice(index, 1)
	}

	// 操作
	 function handleDo(row:any, act:string) {
		dialogStatus.value = act
		switch (act) {
			case 'act_add':
				dialogFormVisible.value = true
				formText.value = '新建信息'
				formTemp.value = JSON.parse(JSON.stringify(cForm))
				formRules.value = Object.assign({}, cRules)
				fromTempTable.value = [JSON.parse(JSON.stringify(cRow))];
				
				
				nextTick(()=>{
					setTimeout(()=>{dataFormRef.value.clearValidate();},0)
				})
				break
			case 'act_edit':
				dialogFormVisible.value = true
				formText.value = '修改信息';
				formTemp.value = JSON.parse(JSON.stringify(row || multipleSelection.value[0]));
				
				approveTemplateInfo({id:formTemp.value.id}).then((res) => {
					console.log(res)
					formTemp.value = res.data
					fromTempTable.value = res.data.rule;
				}).finally(() => {})
				
				nextTick(()=>{
					setTimeout(()=>{dataFormRef.value.clearValidate();},0)
				})
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break
			default:
				dialogFormVisible.value = true
				formText.value = '查看详情'
				formTemp.value = JSON.parse(JSON.stringify(row || multipleSelection.value[0]))
				
		}
	}
	// 提交数据
	function doData(act:string) {
		const rule:any = [];
		for(var i = 0 ; i <fromTempTable.value.length ;i++)
		{
			const item = fromTempTable.value[i];
			if(item.type == 1)
			{
				rule.push({
					name:item.name,
					type:item.type,
					user:item.userInfo.map(item => item.uid),
				
					level:""
				})
			}
			else
			{
				rule.push({
					name:item.name,
					type:item.type,
					level:item.level,
					user:[],
				})
			}
		}

		dataFormRef.value.validate((valid:any) => {
			if (valid) {
				
				loading.value = true;
				const tempData = JSON.parse(JSON.stringify(formTemp.value))
				const newTempData= {
					rule:rule,
					cid:tempData.cid,
					type:tempData.type
				}
				console.log(newTempData)
				if (tempData.id == undefined) {
					approveTemplateAdd(newTempData).then((res) => {
						dialogFormVisible.value = false
						ElMessage({ message:'信息添加成功',type:'success'})
						handleQuery();
					}).finally(() => {
						loading.value = false;
					})
				 } 
				 else {
					approveTemplateEdit(tempData.id,newTempData).then((res) => {
						dialogFormVisible.value = false
						ElMessage({ message:'信息修改成功',type:'success'});
						handleQuery();
					}).finally(() => {
						loading.value = false;
					})
				}
			}
		})
	}
	
	// 删除表单内容
	function handleDelete(row:any) {
		const Ids =row.id;
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			approveTemplateDel({ id: Ids }).then(() => {
				ElMessage.success("删除成功");
				handleQuery();
			}).finally(() => (loading.value = false));
		});
	}
	
	
	function handleSelectionChange(val:any){
		multipleSelection.value = val
	}
	
	
	// 操作按钮样式
	function buttonType(val) {
		if (val === 1) {
			return 'primary'
		} else {
			return 'info'
		}
	}
	// 获取options 配置项
	function get_options() {
		getShenPlist()
	}
	
	/**
	 * 搜索表单-重置
	 */
	function resetQuery() {
	
		handleQuery();
	}
	
	
	
	
	
	const treeRef = ref();
	const downPeoples= ref<any>([]);
	const xiaofei_id= ref<any>();

	// 完善规则
	function perfectCon(index:number,row:any){

		xiaofei_id.value = index
		let userkey = row.userInfo.map((item : any) => '1_' + item.uid);
		dialogApproveVisible.value = true
		nextTick(() => {
			treeRef.value!.setCheckedKeys(userkey, false);
			downPeoples.value  =row.userInfo
		})
		
	}
	/**
	 * 获取审批人列表
	 */
	function getShenPlist() {
		getDepartmentAndUser().then((res) => {
			departmentAndUserList.value = res.data
		}).finally(() => { })
	}
	
	function nodeClickDown(){
		console.log(treeRef.value!.getCheckedNodes(true))
		downPeoples.value = treeRef.value!.getCheckedNodes(true)
	}
	
	function getAllkeys(){
		fromTempTable.value[xiaofei_id.value].userInfo =  treeRef.value!.getCheckedNodes(true)
		dialogApproveVisible.value =false;
	}
	
	
	onMounted(() => {
		get_options();
		handleQuery();
	});
	
</script>

<style lang="scss" scoped>
.appCont{
	display: flex;
	justify-content: space-between;
}
.appContLeft{
	width: 50%;
}
.appContRight{
	width: 50%;
}
.apli{
	margin-bottom: 10px;
	display: flex;
	justify-content: flex-start;
	align-items: center;
}
.perfect_rule:hover{
	color:#ff0000;
	cursor: pointer;
}
</style>